<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>历史轨迹</title>
    <script type="text/javascript"
            src="https://webapi.amap.com/maps?v=2.0&key=c6fe58a4a387b57d7154bd13d2b33ab5"></script>
    <script src="https://cdn.xueerqin.net/axios-0.24.0/axios.min.js"></script>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"/>
    <link
            rel="stylesheet"
            href="https://cdn.xueerqin.net/vant-2.12.37/index.min.css"
    />
    <!-- 引入 Vue 和 Vant 的 JS 文件 -->
    <script src="https://cdn.xueerqin.net/vue-2.6.14/vue.min.js"></script>
    <script src="https://cdn.xueerqin.net/vant-2.12.37/vant.min.js"></script>
    <style>
        html, body, #app {
            height: 100%;
            width: 100%;
        }

        .triangle-down {
            width: 0;
            height: 0;
            border-left: 10px solid transparent;
            border-right: 10px solid transparent;
            border-top: 20px solid #FFC211;
        }

        .date-triangle {
            width: 0;
            height: 0;
            border-left: 4px solid transparent;
            border-right: 4px solid transparent;
            border-top: 6px solid #000;
        }

        .date-box {
            padding: 0 15px;
            align-items: center;
            height: 50px;
            margin: 0 auto;
            display: flex;
            flex-direction: row;
            width: 100%;
        }

        .date-box .quick-button {
            align-items: center;
            justify-content: center;
            height: 27px;
            border-radius: 27px;
            border: 1px solid #C1C1C1;
            padding: 0 12px;
            display: flex;
            flex-direction: row;
        }

        .date-box .date-label {
            font-size: 15px;
            font-family: PingFang SC;
            font-weight: bold;
            color: #232528;
        }

        [v-cloak] {
            display: none;
        }

        .amap-logo {
            display: none !important;
        }

        .amap-copyright {
            display: none !important;
        }

        .hide {
            opacity: 0
        }
    </style>
    <!--    <script src="https://cdn.bootcdn.net/ajax/libs/vConsole/3.4.1/vconsole.min.js"></script>-->
    <!--    <script>-->
    <!--        // init vConsole-->
    <!--        var vConsole = new VConsole();-->
    <!--        console.log('Hello world');-->
    <!--    </script>-->
</head>
<body>
<div id="app" v-cloak>
    <div class="date-box">
        <div class="quick-button" @click="changeDate(-1)">
            <span>前一天</span>
        </div>
        <div style="align-items: center;justify-content: center;display: flex;flex: 1" @click="showDatePicker = true">
            <span class="date-label">{{dateLabel}}</span>
            <div class="date-triangle" style="margin-left: 6px"></div>
        </div>

        <div class="quick-button" @click="changeDate(1)" :class="{'hide': bDisableNextDay}">
            <span>后一天</span>
        </div>
    </div>
    <van-popup v-model="showDatePicker" position="bottom">
        <van-datetime-picker
                v-model="pickerDate"
                @confirm="setTrajectoryDate"
                type="date"
                title="选择年月日"
                active-color="#FED033"
                :max-date="endDate"
        />
    </van-popup>

    <div id="container" style="position:fixed;top: 50px;bottom: 0;width: 100%"></div>

    <!-- 轨迹信息 -->
    <div style="position:fixed;bottom:12px;height:149px;left: 15px;right: 15px;">
        <div style="height:149px;border-radius:12px;background-color:#FFF;transition:all 0.2s ease-in 0s;overflow:hidden;box-shadow:0px 7px 16px 0px rgba(0,0,0,0.15);margin:0 auto;">
            <div style="margin-top: 20px;padding: 0 15px;position: relative">
                <div style="display: flex;flex-direction: row;">
                    <div style="flex: 1" v-if="positionList.length">
                        <p style="font-size:16px;font-family:PingFang SC;font-weight:500;color:#232528;margin-top:8px;">
                            {{positionList[position].address}}</p>
                        <p style="font-size:13px;font-family:PingFang SC;font-weight:500;color:#72777D;margin-top:8px;"
                           v-if="positionList[position].stayMinutes > 5">
                            {{positionList[position].stayText}}</p>
                    </div>
                    <div style="flex: 1" v-if="!positionList.length">
                        <p style="font-size:16px;font-family:PingFang SC;font-weight:500;color:#232528;margin-top:8px;">
                            暂无轨迹</p>
                    </div>
                    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;"
                         @click="playTrajectory" v-if="positionList.length">
                        <img src="https://public-server-center-prod-1258963190.cos.ap-guangzhou.myqcloud.com/studentCard/play.png"
                             v-if="isPauseMove || !isPlaying"
                             style="width: 28px;height: 28px"/>
                        <img src="https://public-server-center-prod-1258963190.cos.ap-guangzhou.myqcloud.com/studentCard/puase.png"
                             v-if="!isPauseMove && isPlaying"
                             style="width: 28px;height: 28px"/>
                        <p style="font-size:13px;font-family:PingFang SC;font-weight:500;color:#72777D;margin-top:8px;">
                            播放轨迹</p>
                    </div>
                </div>

                <div style="margin: 20px 0">
                    <van-slider v-model="position" :min="0" :max="lineArr.length - 1" @input="onChange"
                                @drag-start="slideDragStart" @drag-end="onSliderMove = false"/>
                </div>

                <div style="margin-top: 10px;display: flex;flex-direction: row">
                    <span style="font-size:13px;font-family:PingFang SC;font-weight:500;color:#535558;flex: 1;">起点</span>
                    <span style="font-size:13px;font-family:PingFang SC;font-weight:500;color:#535558;">终点</span>
                </div>
                <div style="position:absolute;bottom: 0;height:60px;width: 100%;" v-if="isPlaying"></div>
            </div>


        </div>
    </div>


    <!--    <div style="position: fixed;top: 50px;left: 0;right: 0;bottom: 0;display: flex;align-items: center;justify-content: center"-->
    <!--         v-if="isPlaying" @click="togglePlay">-->
    <!--        <img src="http://public-server-center-test-1258963190.cos.ap-guangzhou.myqcloud.com/studentCard/2021/6/2/08711404126959771622612631341.png"-->
    <!--             style="width: 60px;height: 60px;z-index: 9" v-if="isPauseMove"/>-->
    <!--    </div>-->
</div>

<script type="text/javascript">

    var urlEncode = function (param, key, encode) {
        if (param == null) return '';
        var paramStr = '';
        var t = typeof (param);
        if (t == 'string' || t == 'number' || t == 'boolean') {
            paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
        } else {
            for (var i in param) {
                var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
                paramStr += urlEncode(param[i], k, encode);
            }
        }
        return paramStr;
    };

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return '';
    }

    secondToHourMinute = (value) => {

        var theTime = parseInt(value);// 秒
        var middle = 0;// 分
        var hour = 0;// 小时

        if (theTime > 60) {
            middle = parseInt(theTime / 60);
            theTime = parseInt(theTime % 60);
            if (middle > 60) {
                hour = parseInt(middle / 60);
                middle = parseInt(middle % 60);
            }
        }
        var result = "" + parseInt(theTime) + "秒";
        if (middle > 0) {
            result = "" + parseInt(middle) + "分" + result;
        }
        if (hour > 0) {
            result = "" + parseInt(hour) + "小时" + result;
        }
        return result;
    }
    new Vue({
        el: '#app',
        data: {
            position: 0,
            positionList: [],
            marker: null,
            lineArr: [],
            onSliderMove: false,
            dateLabel: '今天',
            showDatePicker: false,
            bDisableNextDay: true,
            date: '',
            pickerDate: new Date(),
            endDate: '',
            bMapMoveLoaded: false,
            mapInstance: null,
            avatar: decodeURIComponent(getQueryVariable('avatar')),
            isPlaying: false,
            isPauseMove: false,
            timer: null,
            isFinishMove: true,
            api: 'https://test.card-edu.fjfuyu.net'
        },

        created() {
            if (window.location.host === 's-busi.xueerqin.net') {
                this.api = 'https://stag.card-edu.fjfuyu.net'
            } else if (window.location.host === 'busi.xueerqin.net') {
                this.api = 'https://card-edu.fjfuyu.net'
            } else {
                this.api = 'https://test.card-edu.fjfuyu.net'
            }
            // this.api = 'https://card-edu.fjfuyu.net'

            this.createMapInstance()
            this.date = this.datetime(new Date()).substr(0, 10)
            // this.date = '2021-05-31'
            this.endDate = new Date()
            this.getTrajectoryList()

        },

        methods: {

            createMapInstance() {
                AMap.plugin('AMap.MoveAnimation', () => {
                    this.bMapMoveLoaded = true
                    setTimeout(function () {
                        this.mapInstance = new AMap.Map("container", {
                            resizeEnable: true,
                            zoom: 16,
                            // features: ['bg', 'road', 'point'],
                            rotateEnable: false,
                            pitchEnable: false,
                            pitch: 45,
                            // viewMode: '3D'
                            //
                        });
                        // var satellite = new AMap.TileLayer.Satellite({
                        //     map: this.mapInstance,
                        // });
                        // satellite.setMap(this.mapInstance);
                        // var satelliteLayer = new AMap.TileLayer.Satellite();
                        // var roadNetLayer = new AMap.TileLayer.RoadNet();
                        // this.mapInstance.add([satelliteLayer, roadNetLayer]);
                        // this.mapInstance.setZoom(20)
                    }.bind(this), 100)
                })
            },

            datetime(oDate) {
                const year = oDate.getFullYear()
                const month = oDate.getMonth() + 1
                const day = oDate.getDate()
                const hour = oDate.getHours()
                const minute = oDate.getMinutes()
                const second = oDate.getSeconds()
                return [year, month, day].map(function (n) {
                    n = n.toString()
                    return n[1] ? n : `0${n}`
                }).join('/') + ' ' + [hour, minute, second].map(function (n) {
                    return ('0' + n).substr(-2, 2)
                }).join(':')
            },

            // 前一天后一天
            changeDate(days) {
                days = Number(days)
                if (days > 0 && this.bDisableNextDay) return
                let date = this.datetime(new Date((new Date(this.date)).getTime() + days * 86400 * 1000))
                date = date.substr(0, 10)
                this.setTrajectoryDate(date)
            },

            // 设置日期
            setTrajectoryDate(date) {
                date = this.datetime(new Date(date)).substr(0, 10)
                this.showDatePicker = false
                let today = this.datetime(new Date()).substr(0, 10)
                this.date = date
                this.dateLabel = date === today ? '今天' : date.replace('/\//g', '-')
                this.bDisableNextDay = (new Date(date)).getTime() >= (new Date(today)).getTime()
                this.getTrajectoryList()
            },

            markerContent() {
                // let point = this.positionList.length ? this.positionList[this.position]
                let time = this.positionList.length ? this.positionList[this.position].time : ''
                let markerContent = `
<div style="display: flex;align-items: center;flex-direction: column">
    <div style="background:#FFF;border-radius:5px;font-size:14px;font-family:PingFang SC;font-weight:500;color:#333333;text-align:center;padding:0 8px;box-shadow:0px 5px 8px 0px rgba(0,0,0,0.1);line-height: 27px">
        <span>${time}</span>
    </div>
    <div style="width: 58px;height: 58px;background: #FFC211;border-radius: 50%;align-items: center;justify-content: center;margin-top: 3px;display: flex;position: relative">
        <img src="` + (this.avatar) + `" style="width: 44px;height: 44px;border-radius:50%">
        <div class="triangle-down" style="position:absolute;bottom: -10px;z-index: -1"></div>
    </div>

    <div style="width: 14px;height:14px;background: #FFFFFF;border-radius: 50%;display: flex;align-items: center;justify-content: center;margin-top: 10px">
        <div style="width: 10px;height: 10px;border-radius: 50%;background: #128FEF"></div>
    </div>
</div>
`;
                return markerContent
            },

            // 获取数据
            async getTrajectoryList() {
                let date = this.date.replace('/\//g', '-')
                this.initTrajectory()
                const res = await axios.get(this.api + '/api/app/position/mini-program-gps-aoi-list', {
                    params: {
                        StudentDeviceId: getQueryVariable('studentDeviceId'),
                        BeginTime: date + ' 00:00:00',
                        EndTime: date + ' 23:59:59',
                        PageNum: 1,
                        PageSize: 10000,
                        DayTime: date
                    }
                })

                const data = res.data
                let positionList = []
                data.items.forEach(item => {
                    positionList.push({
                        title: '',
                        time: item.createTime.substr(11, 5),
                        address: '在' + (item.aoi_Name || item.c_Address) + '附近',
                        stayText: '已停留' + secondToHourMinute(item.stayMinutes * 60).replace('0秒', ''),
                        stayMinutes: item.stayMinutes,
                        // location: {
                        //     latitude: Number(item.aoi_Latitude) || Number(item.c_Latitude),
                        //     longitude: Number(item.aoi_Longitude) || Number(item.c_Longitude)
                        // },
                        location: {
                            latitude: Number(item.c_Latitude),
                            longitude: Number(item.c_Longitude) 
                        }
                    })
                })
                this.positionList = positionList
                setTimeout(() => {
                    this.buildMarker()
                }, 100)
            },

            initTrajectory() {
                this.position = 0
                this.isPlaying = false
                this.isFinishMove = true
                this.marker && this.marker.stopMove()
            },

            // 播放轨迹
            playTrajectory() {
                if (!this.isPlaying) {
                    this.initTrajectory()
                    this.isPlaying = true
                    this.marker.moveAlong(this.lineArr, {
                        duration: 1500,
                        autoRotation: false,
                    });
                } else {
                    console.log('===========')
                    this.togglePlay()
                }
            },

            // 暂停轨迹
            pausePlay() {
                this.marker.pauseMove()
            },

            // 继续轨迹
            resumeMove() {
                this.marker.resumeMove()
            },

            slideDragStart() {
                console.log('slideDragStart')
                this.onSliderMove = true
                this.marker.stopMove()
                this.isPlaying = false
            },

            togglePlay() {
                this.timer && clearTimeout(this.timer)
                this.isPauseMove ? this.resumeMove() : this.pausePlay()
                this.isPauseMove = !this.isPauseMove
            },

            onChange(e) {
                this.initTrajectory()
                console.log('========', e)
                if (e < 0) e = 0;
                this.position = e

                this.marker && this.marker.moveTo(this.lineArr[this.position], {
                    duration: 0,
                    autoRotation: false,
                })
            },

            buildMarker() {
                this.mapInstance.clearMap();
                let lineArr = []
                this.positionList.forEach(item => {
                    lineArr.push([item.location.longitude, item.location.latitude])
                })
                if (!this.positionList.length) return
                this.lineArr = lineArr
                this.marker = new AMap.Marker({
                    map: this.mapInstance,
                    position: lineArr[0],
                    content: this.markerContent(),
                    offset: new AMap.Pixel(-30, -108)
                });
                this.mapInstance.setCenter(lineArr[0])
                // 绘制轨迹
                var polyline = new AMap.Polyline({
                    map: this.mapInstance,
                    path: lineArr,
                    showDir: true,
                    strokeColor: "#28F",
                    strokeWeight: 6,
                    strokeStyle: "solid",
                    strokeOpacity: 1
                });

                this.marker.on('moving', function (e) {
                    if (!this.onSliderMove && e.progress === 1) {
                        console.log('=========')
                        this.position = e.passedPath.length - 1
                        if (this.positionList[this.position].stayMinutes > 5) {
                            console.log('========')
                            setTimeout(() => {
                                this.marker.pauseMove()
                            }, 10)
                            this.timer = setTimeout(() => {
                                this.marker.resumeMove()
                            }, 2000)
                        }
                    }
                    if (this.onSliderMove || e.progress === 1) {
                        this.marker.setContent(this.markerContent())
                    }
                    this.mapInstance.setCenter(e.target.getPosition())
                }.bind(this));
                this.mapInstance.setFitView();
                this.marker.on('movealong', () => {
                    this.isPlaying = false
                    this.isFinishMove = true
                })
            }

        }
    })
    ;


</script>
</body>
</html>